import numpy as np
import platform

if platform.uname().node == "sipeed":
    from io import BytesIO
    from PIL import Image
    from maix import camera, mjpg, utils, display, image
else:
    import cv2

READ_TYPE = "socket"    # url socket

MJPEG_HOST = "192.168.2.207"
MJPEG_PORT = 8080
MJPEG_QUERY = "/?action=stream"


def img_data_show(jpg):
    global img_bytes
    global tmp_file
    global is_sipeed
    global BytesIO
    global Image
    global np
    global image
    global display

    if is_sipeed:
        if True:
            bytes_stream = BytesIO(jpg)
            pimg = Image.open(bytes_stream)
            img = image.load(pimg)
            display.show(img)
        else:
            with open(tmp_file, "wb") as binary_file:
                binary_file.write(jpg)
                img = image.open(tmp_file)
                display.show(img)
    else:
        img = cv2.imdecode(np.frombuffer(
            jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
        cv2.imshow('i', img)
        if cv2.waitKey(1) == 27:
            exit(0)


def img_data_match(chunk):
    global img_bytes
    global tmp_file
    global is_sipeed
    global BytesIO
    global Image
    global np
    global image
    global display
    global img_data_show

    img_bytes += chunk
    a = img_bytes.find(b'\xff\xd8')
    b = img_bytes.find(b'\xff\xd9')
    if a != -1 and b != -1:
        jpg = img_bytes[a:b+2]
        img_bytes = img_bytes[b+2:]
        img_data_show(jpg)     


img_bytes = b''
tmp_file = "/tmp/test.jpg"
is_sipeed = platform.uname().node == "sipeed"

print("Connect to %s:%d with %s on %s" % (MJPEG_HOST, MJPEG_PORT, READ_TYPE, platform.uname().node))

if READ_TYPE == "url":
    import requests

    MJPEG_URL = "http://%s:%s%s" % (MJPEG_HOST, MJPEG_PORT, MJPEG_QUERY)

    r = requests.get(MJPEG_URL, stream=True)
    if(r.status_code == 200):
        print("connect success!")
        for chunk in r.iter_content(chunk_size=1024):
            img_data_match(chunk)
    else:
        print("Received unexpected status code {}".format(r.status_code))
elif READ_TYPE == "socket":
    import socket

    client = socket.socket()  # 创建socket套接字
    ret = client.connect((MJPEG_HOST, MJPEG_PORT))  # 状态位，判定是否连接成功
    request_url = "GET %s HTTP/1.1\r\nHost:%s\r\nConnection:Close\r\n\r\n" % (
        MJPEG_QUERY, MJPEG_HOST)

    if(ret == -1):  # 连接失败，退出程序
        print("connet error!")
        exit(-1)
    else:  # 连接成功
        print("connect success!")

    client.send(request_url.encode())  # 发送socket请求，开始接收数据
    chunk = client.recv(1024)  # 第一个recv返回信息，跟图片无关
    chunk = client.recv(1024)  # 这个信息开始跟图片有关系，放到接收变量里
    while chunk:  # 判断是否还有信息
        img_data_match(chunk)
        chunk = client.recv(1024)  # 继续接收
